﻿#pragma once

#include "../box/coro_runner.hh"
#include <cstdint>
#include <unordered_set>

namespace kratos {
namespace service {

class ServiceContextImpl;

/**
 * 协程运行器实现类
 */
class CoroRunnerImpl : public CoroRunner {
  using CoroSet = std::unordered_set<std::uint64_t>;
  CoroSet coro_set_;                 ///< 协程表
  ServiceContextImpl *ctx_{nullptr}; ///< 容器上下文

public:
  CoroRunnerImpl(ServiceContextImpl *ctx);
  virtual ~CoroRunnerImpl();
  virtual auto start_co(CoFunction func) -> COID override;
  virtual auto sleep_co(std::time_t ms) -> void override;
  virtual auto yield_co() -> void override;
  virtual auto resume_co(COID coid) -> void override;
  virtual auto try_co() -> std::any override;
  virtual auto wait_co() -> std::any override;
  virtual auto wait_co(std::time_t timeout) -> std::any override;
  virtual auto await_cancel_co(std::time_t timeout, CoFunction func)
      -> bool override;
  virtual auto push_co(COID coid, std::any &data) -> bool override;
  virtual auto cancel_co(COID coid) -> void override;
  virtual auto stop_all_co() -> void override;
  virtual auto get_id() -> COID override;

private:
  /**
   * 运行协程
   * @param cof 协程函数
   */
  void run(CoFunction cof);
};

} // namespace service
} // namespace kratos
